﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace Reborn_WorldServer.PendingClusterQuerys
{
    public class PendingQueryManager
    {
        private List<GlobalWhoRequest> pendingWhoRequests = new List<GlobalWhoRequest>();

        public void sendGlobalWho(GlobalWhoRequest globalWho)
        {
            lock (pendingWhoRequests)
            {
                bool requestExists = false;
                foreach (GlobalWhoRequest pendingRequest in pendingWhoRequests)
                {
                    if (pendingRequest.character.ID == globalWho.character.ID)
                    {
                        requestExists = true;
                        break;
                    }
                }
                if (requestExists == false)
                {
                    pendingWhoRequests.Add(globalWho);
                    Managers.BeginSendToPrimary("<globalwhorequest characterid=\"" + globalWho.character.ID.ToString() + "\" />");
                }
            }
        }
        public void pendingWhoTimeout(GlobalWhoRequest pendingRequest)
        {
            lock (pendingWhoRequests)
            {
                if (pendingWhoRequests.Contains(pendingRequest))
                {
                    pendingWhoRequests.Remove(pendingRequest);
                    pendingRequest.processResult(null);
                }
            }
        }
        public void processWhoResult(int characterId, string xmlMessage)
        {
            //Get list of friend IDs we're going to query from the other world servers
            List<string> charactersOnline = new List<string>();

            if (xmlMessage != "")
            {
                StringReader sr = new StringReader(xmlMessage);
                XmlTextReader xmlReader = new XmlTextReader(sr);
                while (xmlReader.Read())
                {
                    if (xmlReader.Name == "characteronline" && xmlReader.IsStartElement())
                        charactersOnline.Add(xmlReader.ReadString());
                }
            }

            lock (pendingWhoRequests)
            {
                foreach (GlobalWhoRequest pendingRequest in pendingWhoRequests)
                {
                    if (pendingRequest.character.ID == characterId)
                    {
                        pendingWhoRequests.Remove(pendingRequest);
                        pendingRequest.processResult(charactersOnline);
                        break;
                    }
                }
            }
        }
        
    }
}
